#include <ESP8266WiFi.h>
#include <PubSubClient.h>

/*WiFi配置*/
const char *ssid = "OrayBox-2.4G-9210";
const char *password = "00000000";

/*MQTT服务器配置*/
const char *mqtt_broker = "47.95.42.143";// EMQX broker endpoint
const char *mqtt_topic = "g29";// MQTT topic
const char *mqtt_username = "000";// MQTT username for authentication
const char *mqtt_password = "000";// MQTT password for authentication
const int mqtt_port = 1883;// MQTT port (TCP)

/*LED状态*/
uint8_t led_status = 0;
uint32_t tick = 0;
uint32_t last_tick = 0;

/*创建对象*/
WiFiClient wifi_client;
PubSubClient mqtt_client(wifi_client);

/*连接MQTT服务器*/
void connect_to_mqtt_broker()
{
  while(!mqtt_client.connected())
  {
    String client_id = "esp8266-client-" + String(WiFi.macAddress());
    printf("Connecting to MQTT Broker...\n");
    if(mqtt_client.connect(client_id.c_str(), mqtt_username, mqtt_password))
    {
      printf("Connected to MQTT broker.\n");
      mqtt_client.subscribe(mqtt_topic);
    }else
    {
      printf("Failed to connected to MQTT broker.status:%d\n",mqtt_client.state());
      printf("Try again in 1s.");
      delay(100);
    }
  }
}

/*回调函数*/
void mqtt_cb(char *topic,byte *payload,unsigned int length)
{
  for(int i = 0;i < length;i++)
  {
    Serial.print((char)payload[i]);
  }
}

void setup() {
  // put your setup code here, to run once:
  /*初始化外设*/
  Serial.begin(115200);
  printf("\n\n");
  pinMode(LED_BUILTIN, OUTPUT);
  /*连接WiFi*/
  WiFi.begin(ssid,password);
  printf("Connecting to WiFi...\n");
  while(WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    printf(".");
  }
  printf("\nConnected to the WiFi network.\n");
  /*设置MQTT broker*/
  mqtt_client.setServer(mqtt_broker,mqtt_port);
  mqtt_client.setCallback(mqtt_cb);
  connect_to_mqtt_broker();
}

void loop() {
  // put your main code here, to run repeatedly:

  /*LED闪烁*/
  tick = millis();
  if((tick - last_tick) > 500)
  {
    last_tick = tick;
    led_status = !led_status;
    digitalWrite(LED_BUILTIN, led_status);
  }

  /*处理MQTT*/
  if(!mqtt_client.connected())
  {
    connect_to_mqtt_broker();
  }
  mqtt_client.loop();
}
